package com.nuanshui.heatedloan.extension;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.nuanshui.framework.lang.SysStringUtils;


public class SetMethodProcessor implements HandlerMethodArgumentResolver{

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return Set.class.isAssignableFrom(parameter.getParameterType());

	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		Class<?> paramterType =  parameter.getParameterType();
		String name = parameter.getParameterName();
		Type type =  parameter.getGenericParameterType();
		Class<?> argument = getactualTypeArgument(type);
		String values[] = webRequest.getParameterValues(name);
		Set<Object> set  = null;
		if(paramterType == LinkedHashSet.class) {
			set  = new LinkedHashSet<Object>();
		}else {
			set = new HashSet<Object>();
		}
		if(values != null) {
			for(String  value :values){
				if(SysStringUtils.isEmpty(value)) continue;
		    	if(argument == Long.class) {
		    		set.add(Long.parseLong(value));
		    	}else {
		    		set.add(value);
		    	}
		    }
		}
		return set;
	}
	
    private Class<?> getactualTypeArgument(Type type) {
    	if (type instanceof ParameterizedType) {     
    		   ParameterizedType paramType = (ParameterizedType) type;     
    		   Type[] actualTypes = paramType.getActualTypeArguments();     
    		   for (Type aType : actualTypes) {         
    		       if (aType instanceof Class) {         
    		           Class<?> clz = (Class<?>) aType;             
    		           return clz;
    		       }     
    		   } 
    	}
    	return Object.class;
    	
    }

}
